package com.ethen.liveeventbus.slice;

import android.life.livedata.Observer;
import android.log.Log;
import com.ethen.liveeventbus.ResourceTable;
import com.ohos.liveeventbus.LiveEventBus;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.ToastDialog;

public class LiveEventAbilitySlice extends AbilitySlice {
    private static final String TAG = "LiveEventAbilitySlice";
    private static final String KEY1 = "event_live";
    private static final String KEY2 = "event_live2";
    private static final String KEY3 = "event_live3";

    private Observer<String> foreverOb;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_life_request_layout);
        LifeAbilitySlice2 life2 = new LifeAbilitySlice2();

        findComponentById(ResourceTable.Id_btn_life).setClickedListener(component -> {
            LiveEventBus.get(KEY1).post("hi ethen!");
        });

        findComponentById(ResourceTable.Id_btn_life_global).setClickedListener(component -> {
            LiveEventBus.get(KEY1).post(23);
        });

        findComponentById(ResourceTable.Id_btn_life2).setClickedListener(component -> {
            LiveEventBus.get(KEY2).post("hi ethen2222!");
        });

        findComponentById(ResourceTable.Id_btn_process).setClickedListener(component -> {
            LiveEventBus.get(KEY3).postAcrossApp("hi ethen2222!");
        });

        findComponentById(ResourceTable.Id_btn_to_life2).setClickedListener(component -> {
            present(life2, new Intent());
        });

        initObserve1();
        initObserverForever();
    }

    private void initObserve1() {
        LiveEventBus.get(KEY1, String.class).observe(this, s -> {
            new ToastDialog(getContext()).setText(s).setDuration(1000).show();
            Log.d(TAG, "get String.class,key: " + KEY1 + ",value is:" + s);
        });

        LiveEventBus.get(KEY1, Integer.class).observe(this, s -> {
            new ToastDialog(getContext()).setText(String.valueOf(s)).setDuration(1000).show();
            Log.d(TAG, "get Int.class,key: " + KEY1 + ",value is:" + s);
        });
    }

    private void initObserverForever() {
        foreverOb = new Observer<String>() {
            @Override
            public void onChanged(String s) {
                new ToastDialog(getContext()).setText(s).setDuration(1000).show();
                Log.d(TAG, "get Forever String.class,key: " + KEY2 + ",value is:" + s);
            }
        };
        LiveEventBus.get(KEY2, String.class).observeForever(foreverOb);
    }

    @Override
    protected void onStop() {
        super.onStop();
        LiveEventBus.get(KEY2, String.class).removeObserver(foreverOb);
    }
}
